package 二叉树;

public class LC_513找树左下角的值 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int maxDepth=Integer.MIN_VALUE;
    int result;
    public int findBottomLeftValue(TreeNode root) {
        //只要先遍历左即可，前中后序均可
        int depth=0;
        travel(root,depth);
        return result;
    }
    public void travel(TreeNode root,int depth){
        if(root.left==null && root.right==null){
            if(depth>maxDepth){
                maxDepth=depth;
                result=root.val;
            }
        }
        //左
        if(root.left!=null){
            depth++;
            travel(root.left,depth);
            depth--;//回溯
            //简洁版：travel(root.left,depth+1);
        }
        //右
        if(root.right!=null){
            depth++;
            travel(root.right,depth);
            depth--;//回溯
        }
    }
}
